package cn.ecnu.auction.engine;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import cn.ecnu.auction.db.DbConnection;

public class ServiceManager {
	
	private static HashMap<String, IService> serviceManager = null;
	
	public static void init(Context context){
		serviceManager = new HashMap<String, IService>();
		Connection conn = DbConnection.getConnection();
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select serviceName, className from t_service");
			while (rs.next()) 
			{
				try
				{
					serviceManager.put(rs.getString(1), (IService)Class.forName(rs.getString(2)).newInstance());
				}
				catch(Exception ex)
				{
					ex.printStackTrace();
				}
			}			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		finally
		{
			DbConnection.closeConnection(conn);
		}
	}
	
	public static IService getService(Context context){
		IService service = null;
		
		if(null == serviceManager){
			init(context);
		}
		service = serviceManager.get(context.getServiceName());
		
		return service;
	}
}
